package com.wyc.example.controller;

import com.wyc.example.common.Result;
import com.wyc.example.entity.User;
import com.wyc.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

/**
 * @author 王韫琛
 * @version 1.0
 * @date 2021/5/23 9:31
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * @Author 王韫琛
     * @Description //TODO 新增用户
     * @Date 11:00 2021/5/23
     * @Param [user]
     * @return com.wyc.example.common.Result
     **/
    @PostMapping
    public Result add(@RequestBody User user){
        userService.save(user);
        return Result.success();
    }
    /**
     * @Author 王韫琛
     * @Description //TODO 更新用户
     * @Date 11:01 2021/5/23
     * @Param [user]
     * @return com.wyc.example.common.Result
     **/
    @PutMapping
    public Result update(@RequestBody User user){
        userService.save(user);
        return Result.success();
    }
    /**
     * @Author 王韫琛
     * @Description //TODO 删除用户
     * @Date 11:13 2021/5/23
     * @Param [id]
     * @return com.wyc.example.common.Result
     **/
    @DeleteMapping("/{id}")
    public Result delete (@PathVariable Long id){
        userService.del(id);
        return Result.success();
    }
    /**
     * @Author 王韫琛
     * @Description //TODO 根据di查询用户信息
     * @Date 11:23 2021/5/23
     * @Param [id]
     * @return com.wyc.example.common.Result<com.wyc.example.entity.User>
     **/
    @GetMapping("/{id}")
    public Result<User> findById(@PathVariable Long id){
        return Result.success(userService.findById(id));
    }
    /**
     * @Author 王韫琛
     * @Description //TODO 分页模糊查询.
     * @RequestParam 和 @PathVariable 注解是用于从request中接收请求的，两个都可以接收参数
     * 关键点不同的是@RequestParam 是从request里面拿取值，而 @PathVariable 是从一个URI模板里面来填充
     * @Date 11:37 2021/5/23
     * @Param [pageNum, pageSize, name]
     * @return com.wyc.example.common.Result<com.wyc.example.entity.User>
     **/
    // 分页查询用户
    @GetMapping("/page")
    public Result<Page<User>> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                       @RequestParam(defaultValue = "10") Integer pageSize,
                                       @RequestParam(required = false) String name) {
        return Result.success(userService.findPage(pageNum, pageSize, name));
    }
}
